import React, { Component } from 'react';
import {
	View, Text, StyleSheet, TouchableOpacity, Image,
	PixelRatio, ListView, Platform, Modal, TextInput
} from 'react-native';
import { GLOBAL } from '../../../config/global';
import { style } from '../../../theme/style';
import { API, API_GENERATE } from '../../../config/api';
import HTTP from '../../../utils/http';
import { PageStatusIndex } from '../../../component/page-status/PageStatusIndex';

const scale = GLOBAL.SCALE;
const ds = new ListView.DataSource({ rowHasChanged: (r1, r2) => r1 !== r2 });

const optionPicSourse = require('../../../imgs/global/option.png');
const selectedPicSourse = require('../../../imgs/global/success.png');

let goodsSelected;
export default class ProductSelectAll extends Component {

	constructor(props) {
		super(props);
		goodsSelected = this.props.goodsSelected || {};
		console.log('goodsSelected', goodsSelected)
		this.state = {
			category1List: [],
			category2List: [],
			category3List: [],
			curCategory1: '',
			curCategory2: '',
			category3Selected: goodsSelected,
			status: 'loading'
		}
		this.productArray = [];
		this.renderCategory1 = this.renderCategory1.bind(this);
		this.renderCategory2 = this.renderCategory2.bind(this);
		this.renderCategory3 = this.renderCategory3.bind(this);


		this.goodsName = '';
	}



	// 默认属性设置
	static defaultProps = {
		visible: false
	};

	//  获取商品数据
	_getGoodsData = async () => {
		this.setState({
			status: 'loading'
		})
		let sendData = {};
		if (this.goodsName != '') {
			sendData.goodsName = this.goodsName;
		}
		let responseData = await HTTP.POST(API_GENERATE(API.GET_PRODUCT_TREE), sendData);
		this.setState({
			status: responseData && responseData.length > 0 ? 'data' : 'empty'
		})
		return responseData
	}

	//根据数据 初始化demo
	_init = () => {
		let { category1List, category2List, category3List, curCategory1, curCategory2, category3Selected } = this.state;
		if (this.productArray && this.productArray.length) {
			//因PC端删除某产品的权限，详情查出的无权限产品应该在确认时进行清除，以免点击下一步时权限校验不通过
			if (category3Selected) {
				let ifHas = {};
				for (let key in category3Selected) {
					this.productArray.map((category1) => {
						const { children } = category1;
						children.map((category2, index2) => {
							const { children } = category2;
							children.map((category3, index3) => {
								const { goodsCategoryVO, } = category3;
								const { goodsCateId } = goodsCategoryVO;
								if (key === goodsCateId) {
									ifHas[key] = category3Selected[key];
								}
							})
						})
					})
				}
				this.setState({ category3Selected: ifHas })
			}

			//初始化已勾选选项的状态
			category1List = this.productArray.map((category1, index1) => {
				const { goodsCategoryVO, children } = category1;
				const { goodsCateId, goodsCateName } = goodsCategoryVO;
				if (index1 == 0) {
					curCategory1 = goodsCateId;
					if (children && children.length) {
						category2List = children.map((category2, index2) => {
							const { goodsCategoryVO, children } = category2;
							const { goodsCateId, goodsCateName } = goodsCategoryVO;
							if (index2 == 0) {
								curCategory2 = goodsCateId;
								if (children && children.length > 0) {
									let checkItems = []; let checkAll = {};
									category3List = children.map((category3, index3) => {
										const { goodsCategoryVO, } = category3;
										const { goodsCateId, goodsCateName } = goodsCategoryVO;
										if (this.state.category3Selected[goodsCateId] && this.state.category3Selected[goodsCateId]['check'] && this.state.category3Selected[goodsCateId]['goodsCateName'] !== '选择全部') {
											checkItems.push(category3);
										}
										return { goodsCateId, goodsCateName, }
									})

									//添加选择全部，并且根据选中状态判断是不是全部选中
									checkAll = {
										check: false,
										goodsCateId: category1.goodsCategoryVO.goodsCateId + category2.goodsCategoryVO.goodsCateId,
										goodsCateName: '选择全部'
									}
									if (checkItems.length === children.length) {
										checkAll['check'] = true;
										goodsSelected[category1.goodsCategoryVO.goodsCateId + category2.goodsCategoryVO.goodsCateId] = checkAll;
										this.setState({
											category3Selected: goodsSelected
										})
									}
									category3List.unshift(checkAll);
								}
							}
							return { goodsCateId, goodsCateName, }
						})
					}
				}

				return { goodsCateId, goodsCateName, }
			})
			this.setState({
				category1List, category2List, category3List, curCategory1, curCategory2,
			});
		}
	}



	async componentWillMount() {
		this.productArray = await this._getGoodsData();
		await this._init();
	}

	//搜索文字
	_writeFn = (val) => {
		this.goodsName = val.replace(/(^\s*)|(\s*$)/g, "");
		if (this.goodsName == '') {
			this._searchFn();
		}
	}

	//搜索
	_searchFn = () => {
		let { sideCheckData, mainCheckData } = this.state;
		this.setState({
			category1List: [],
			category2List: [],
			category3List: [],
			curCategory1: '',
			curCategory2: '',
		}, async () => {
			this.productArray = await this._getGoodsData();
			this._init();
		})
	}

	render() {
		const { visible, cancelPress } = this.props;
		const { category1List, category2List, category3List, curCategory1, curCategory2, category3Selected, status } = this.state;
		const category1Source = ds.cloneWithRows(category1List);
		const category2Source = ds.cloneWithRows(category2List);
		const category3Source = ds.cloneWithRows(category3List);
		return (
			<Modal animationType={"slide"}
				transparent={true}
				visible={visible}
				onRequestClose={() => { }}>
				<View style={styles.container}>
					<View style={styles.wrap}>

						<View style={styles.head}>
							<TouchableOpacity onPress={
								cancelPress} activeOpacity={0.5}>
								<Text style={styles.headText}>取消</Text>
							</TouchableOpacity>
							<Text style={[styles.headText, { fontSize: 18 * scale, color: '#404040' }]}>选择商品</Text>
							<TouchableOpacity onPress={this._didPressConfirm.bind(this)} activeOpacity={0.5}><Text style={styles.headText}>确定</Text>
							</TouchableOpacity>
						</View>

						<View style={styles.searchBox}>
							<TouchableOpacity activeOpacity={1} onPress={() => { this.refs.searchInput.focus() }} style={styles.searchBg}>
								<Image source={require('../../../imgs/customer/searchLeft.png')} style={styles.searchImg} />
								<TextInput
									ref={'searchInput'}
									style={styles.searcuhInput}
									underlineColorAndroid='transparent'
									placeholder={'搜索商品'}
									onChangeText={(value) => {
										this._writeFn(value);
									}}
									onSubmitEditing={() => {
										this._searchFn();
									}}
									returnKeyType={'search'}
								/>
							</TouchableOpacity>
							<Text style={styles.searchBtn} onPress={this._searchFn}>搜索</Text>
						</View>

						<View style={{ flex: 1 }}>
							{
								(status == 'data') ? (
									<View style={[styles.listViewCell]}>
										<View style={[{ width: 100 * scale }]}>
											<ListView
												style={[styles.listView]}
												dataSource={category1Source}
												renderRow={this.renderCategory1}
												enableEmptySections={true}
											/>
											<View style={styles.androidStyle}></View>
										</View>
										<View style={[{ width: 100 * scale, borderLeftColor: '#e4e4e4', borderLeftWidth: 1 / PixelRatio.get(), }]}>
											<ListView
												style={[styles.listView]}
												dataSource={category2Source}
												renderRow={this.renderCategory2}
												enableEmptySections={true}
											/>
											<View style={styles.androidStyle}></View>
										</View>
										<View style={[{ width: 175 * scale, borderLeftColor: '#e4e4e4', borderLeftWidth: 1 / PixelRatio.get() }]}>
											{
												(category3List && category3List.length > 0) ? (<ListView
													style={[styles.listView]}
													dataSource={category3Source}
													renderRow={this.renderCategory3}
													enableEmptySections={true}
												/>) : (
														<PageStatusIndex status={'empty'} emptyText={'暂无商品'} />
													)
											}
											<View style={styles.androidStyle}></View>
										</View>
									</View>
								) : (
										<PageStatusIndex status={status} emptyText={'暂无商品'} />
									)
							}

						</View>
					</View>
				</View>
			</Modal >
		);
	}
	_didPressConfirm() {
		const { confirmPress } = this.props;
		const { category3Selected } = this.state;
		confirmPress(category3Selected);
	}

	renderCategory3(category) {
		const { goodsCateId, goodsCateName, } = category;
		const { category3Selected } = this.state;
		const source = (category3Selected && category3Selected[goodsCateId] && category3Selected[goodsCateId]['check']) ? selectedPicSourse : optionPicSourse;
		return (
			<TouchableOpacity onPress={this._didPressCategory3.bind(this, category)} activeOpacity={0.5} style={[styles.category2]}>
				<View style={styles.category2left}><Text numberOfLines={2} style={styles.text}>{goodsCateName}</Text></View>
				<View style={styles.category2right}><Image source={source} style={styles.optionPic} /></View>
			</TouchableOpacity>
		);
	}

	renderCategory1(category) {
		const { goodsCateId, goodsCateName, } = category;
		const { curCategory1 } = this.state;
		const style = (goodsCateId == curCategory1) ? styles.curCategory : null;
		return (
			<TouchableOpacity onPress={this._didPressCategory1.bind(this, goodsCateId)} activeOpacity={0.5} style={[styles.category1, style]}>
				<Text style={styles.text}>{goodsCateName}</Text>
			</TouchableOpacity>
		);
	}

	_didPressCategory1(goodsCateId) {
		let { curCategory1, curCategory2, category2List, category3List } = this.state;
		if (goodsCateId != curCategory1) {
			curCategory1 = goodsCateId;
			this.productArray.forEach((category1) => {
				const { children, goodsCategoryVO } = category1;
				const { goodsCateId, } = goodsCategoryVO;
				if (goodsCateId == curCategory1) {
					if (children && children.length) {
						category2List = children.map((category2, index2) => {
							const { goodsCategoryVO, children } = category2;
							const { goodsCateId, goodsCateName } = goodsCategoryVO;
							if (index2 == 0) {
								curCategory2 = goodsCateId;
								if (children && children.length > 0) {
									let checkItems = []; let checkAll = {};

									category3List = children.map((category3, index3) => {
										const { goodsCategoryVO, } = category3;
										const { goodsCateId, goodsCateName } = goodsCategoryVO;
										if (this.state.category3Selected[goodsCateId] && this.state.category3Selected[goodsCateId]['check'] && this.state.category3Selected[goodsCateId]['goodsCateName'] !== '选择全部') {
											checkItems.push(category3);
										}
										return { goodsCateId, goodsCateName, }
									})
									//添加选择全部，并且根据选中状态判断是不是全部选中
									checkAll = {
										check: false,
										goodsCateId: category1.goodsCategoryVO.goodsCateId + category2.goodsCategoryVO.goodsCateId,
										goodsCateName: '选择全部'
									}
									if (checkItems.length === children.length) {
										checkAll['check'] = true;
										goodsSelected[category1.goodsCategoryVO.goodsCateId + category2.goodsCategoryVO.goodsCateId] = checkAll;
										this.setState({
											category3Selected: goodsSelected
										})
									}
									category3List.unshift(checkAll);
								} else {
									category3List = [];
								}
							}
							return { goodsCateId, goodsCateName, }
						})
					}
				}
			});
			this.setState({
				curCategory1, curCategory2, category2List, category3List
			});
		}
	}

	renderCategory2(category) {
		const { goodsCateId, goodsCateName, } = category;
		const { curCategory2 } = this.state;
		const style = (goodsCateId == curCategory2) ? styles.curCategory : null;
		return (
			<TouchableOpacity onPress={this._didPressCategory2.bind(this, goodsCateId)} activeOpacity={0.5} style={[styles.category1, style]}>
				<Text style={styles.text}>{goodsCateName}</Text>
			</TouchableOpacity>
		);
	}

	_didPressCategory2(goodsCateId) {
		let { curCategory1, curCategory2, category3List } = this.state;
		if (goodsCateId != curCategory2) {
			curCategory2 = goodsCateId;
			this.productArray.forEach((category1) => {
				const { children, goodsCategoryVO } = category1;
				const { goodsCateId, } = goodsCategoryVO;
				if (goodsCateId == curCategory1) {
					if (children && children.length) {
						children.forEach((category2) => {
							const { children, goodsCategoryVO } = category2;
							const { goodsCateId, } = goodsCategoryVO;
							if (goodsCateId == curCategory2) {
								if (children && children.length) {
									let checkItems = []; let checkAll = {};
									category3List = children.map((category3) => {
										const { goodsCategoryVO, } = category3;
										const { goodsCateId, goodsCateName } = goodsCategoryVO;
										if (this.state.category3Selected[goodsCateId] && this.state.category3Selected[goodsCateId]['check'] && this.state.category3Selected[goodsCateId]['goodsCateName'] !== '选择全部') {
											checkItems.push(category3);
										}
										return { goodsCateId, goodsCateName, }
									})

									//添加选择全部，并且根据选中状态判断是不是全部选中
									checkAll = {
										check: false,
										goodsCateId: category1.goodsCategoryVO.goodsCateId + category2.goodsCategoryVO.goodsCateId,
										goodsCateName: '选择全部'
									}
									if (checkItems.length === children.length) {
										checkAll['check'] = true;
										goodsSelected[category1.goodsCategoryVO.goodsCateId + category2.goodsCategoryVO.goodsCateId] = checkAll;
										this.setState({
											category3Selected: goodsSelected
										})
									}
									category3List.unshift(checkAll);
								}
							}
						});

					}
				}
			});
			this.setState(
				{ curCategory2, category3List }
			);
		}
	}

	_didPressCategory3(category) {
		const { goodsCateId, goodsCateName } = category;
		const { category3Selected, category3List, curCategory1, curCategory2 } = this.state;
		if (category3Selected[goodsCateId]) {
			category3Selected[goodsCateId]['check'] = !category3Selected[goodsCateId]['check'];
		} else {
			category3Selected[goodsCateId] = category;
			category3Selected[goodsCateId]['check'] = true;
			category3Selected[goodsCateId]['objectId'] = goodsCateId;
		}
		if (goodsCateName == '选择全部') {
			let onOff = category3Selected[goodsCateId]['check'];
			category3List.map((item, index) => {
				category3Selected[item.goodsCateId] = item;
				category3Selected[item.goodsCateId]['objectId'] = item.goodsCateId;
				category3Selected[item.goodsCateId]['check'] = onOff;
			});
		} else {
			let checkItems = []; let checkAll = {};
			category3List.map((category3) => {
				const { goodsCateId, goodsCateName } = category3;
				if (category3Selected[goodsCateId] && category3Selected[goodsCateId]['check'] && category3Selected[goodsCateId]['goodsCateName'] !== '选择全部') {
					checkItems.push(category3);
				}
			})
			//添加选择全部，并且根据选中状态判断是不是全部选中
			category3Selected[curCategory1 + curCategory2] = {
				check: checkItems.length === category3List.length - 1 ? true : false,
				goodsCateId: category.goodsCateId,
				goodsCateName: '选择全部'
			};
		}

		this.setState({
			category3Selected,
		});
	}
}

const styles = StyleSheet.create({
	optionPic: {
		width: 14 * scale,
		height: 14 * scale,
	},
	category1: {
		height: 50 * scale,
		justifyContent: 'center',
		alignItems: 'center',
	},
	category2: {
		flexDirection: 'row',
	},
	category2left: {
		flex: 1,
		justifyContent: 'center',
		paddingLeft: 10 * scale,
	},
	category2right: {
		height: 50 * scale,
		width: 26 * scale,
		justifyContent: 'center',
		marginRight: 2 * scale,
	},
	curCategory: {
		backgroundColor: '#F8F8F8',
	},
	listView: {
		flex: 1,
	},
	listCol: {
		borderLeftColor: '#e4e4e4',
		borderLeftWidth: 1 / PixelRatio.get(),
		borderRightColor: '#e4e4e4',
		borderRightWidth: 1 / PixelRatio.get(),
	},
	listViewCell: {
		flex: 1,
		flexDirection: 'row',
		borderTopColor: '#e4e4e4',
		borderTopWidth: 1 / PixelRatio.get(),
	},
	head: {
		flexDirection: 'row',
		justifyContent: 'space-around',
		height: 52 * scale,
		width: 375 * scale,
		alignItems: 'center',
	},
	headText: {
		fontSize: 16 * scale,
		color: style.color.themeColor,
		paddingTop: 5 * scale,
		paddingBottom: 5 * scale,
		paddingLeft: 8 * scale,
		paddingRight: 8 * scale
	},
	wrap: {
		backgroundColor: '#fff',
		width: 375 * scale,
		height: '70%',
	},
	text: {
		fontSize: 13 * scale,
		color: '#404040'
	},
	container: {
		width: 375 * scale,
		height: GLOBAL.SCREEN_HEIGHT,
		backgroundColor: 'rgba(0, 0, 0, .3)',
		justifyContent: 'flex-end',
	},
	searchBox: {
		height: 45 * scale,
		paddingLeft: 15 * scale,
		paddingTop: 8 * scale,
		paddingBottom: 7 * scale,
		flexDirection: 'row',
		alignItems: 'center',
		borderTopColor: '#e4e4e4',
		borderTopWidth: 1 / PixelRatio.get(),
	},
	searchBg: {
		width: 300 * scale,
		height: 30 * scale,
		backgroundColor: style.color.light,
		borderRadius: 4 * scale,
		flexDirection: 'row',
		alignItems: 'center',
	},
	searchBtn: {
		fontSize: 16 * scale,
		color: style.color.dark,
		marginLeft: 10 * scale,
		padding: 5 * scale
	},
	searchImg: {
		width: 12 * scale,
		height: 11 * scale,
		marginLeft: 20 * scale,
		marginRight: 20 * scale
	},
	searcuhInput: {
		width: 200 * scale,
		paddingVertical: 0,
		height: 18 * scale
	},
	selectNumber: {
		borderRadius: 5 * scale,
		width: 20 * scale,
		height: 14 * scale,
		marginLeft: 5 * scale,
		fontSize: 11 * scale,
		backgroundColor: style.color.themeColor,
		color: style.color.white,
		textAlign: 'center'
	},
	androidStyle: {
		height: 30 * scale,
	}
})